package com.author.server.service.impl;

import com.auth.service.api.Account;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.author.server.service.JwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.lang.model.util.ElementScanner6;
import java.util.Date;

/**
 * @Author:RenPu
 * @Date: 2020/10/28 20:31
 * @Version: 1.0
 * @description:
 */

@Service
//@Slf4j
public class JwtServiceImpl implements JwtService {


    //在生产环境此值是加密后传递过来的
    private static final String KEY = "changeIt";

    //在生产环境此值是加密后传递过来的
    private static final String ISSUER = "renxiaotian";

    private static final long TOKEN_EXP_TIME = 60000;   //设置token的超时间为60s
    private static final String USE_NAME = "username";


    /**
     * 生成tokn
     *
     * @param account
     * @return
     */
    @Override
    public String getToken(Account account) {

        Date now = new Date();

        //制定算法对key进行加密
        Algorithm algorithm = Algorithm.HMAC256(KEY);

        //通过jwt生成token
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)   //此token在什么时间点生产的
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME))   //设置token的过期时间
                .withClaim(USE_NAME, account.getUsername())     //设置自定的参数的传入
                .sign(algorithm);

//        log.info("jwt generated user={}", account.getUsername());
        return token;
    }


    /**
     * 校验token
     *
     * @param username
     * @param token
     * @return
     */
    @Override
    public boolean verify(String username, String token) {

        Algorithm algorithm = Algorithm.HMAC256(KEY);

        try {

            JWTVerifier verifier = JWT.require(algorithm).   //使用同样的算法进行校验；
                    withIssuer(ISSUER)                       //验证用户名称是否相同；
                    .withClaim(USE_NAME, username)            //验证用户名称是否，是相同的；
                    .build();                                //进行一个创建
            verifier.verify(token);                          //验证token
            return true;
        } catch (Exception e) {
//            log.info("auth error o(╥﹏╥)o" + e);
            return false;
        }

    }

    @Override
    public String refresh() {
        return null;
    }
}
